package com.ysz.timewheel.server.struct;


/**
 * @ClassName TimeWheelStruct
 * @Description 定义时间轮的结构体
 * @Data 15:28
 * @Version 1.0
 * @Author ysz
 */
public class TimeWheelStruct {

    /**
     * 时间轮头节点
     */
    private static final Node first;
    /**
     * 时间轮尾节点
     */
    private static final Node last;
    /**
     * 默认容量
     */
    private static final int capacity = 30;


    /**
     * 构建结构体完成结构体的初始化=====>双向循环链表
     */
    static {
        Node node;
        first = new Node();
        first.setPrev(null);
        node = first;
        for (int i = 0; i < capacity - 2; i++) {
            Node member = new Node();
            node.setNext(member);
            member.setPrev(node);
            node = member;
        }
        last = new Node();
        node.setNext(last);
        last.setPrev(node);
        last.setNext(first);
        first.setPrev(last);
    }


    /**
     * 在指定下标位更新元素的时间戳
     *
     * @author ysz
     * @date 2022/2/23 9:49
     */
    public static void addByIndex(int index) {
        if (index < (capacity >> 1)) {
            Node x = first;
            for (int i = 0; i <= index; i++) {
                x = x.getNext();
                if (i == index) {
                    x.setCurrentIndex(index);
                    x.setNumberOfScans(0);
                }
            }
        } else {
            Node x = last;
            for (int i = capacity - 1; i >= index; i--) {
                x = x.getPrev();
                if (i == index) {
                    x.setCurrentIndex(index);
                    x.setNumberOfScans(0);
                }
            }
        }
    }

    public static Node getFirst() {
        return first;
    }

    public static Node getLast() {
        return last;
    }

    public static int getCapacity() {
        return capacity;
    }
}
